#include "wlan.h"

int convert_quality_to_dbm(int quality)
{
    int dbm = 0;
    if (quality <= 0)
        dbm = -100;
    else if (quality >= 100)
        dbm = -50;
    else
        dbm = -100 + quality / 2;
    return dbm;
}

int main(void)
{
    int i;
    DWORD dwError = 0;
    HINSTANCE hInstLibrary;
    HANDLE hClientHandle = NULL;
    DWORD dwNegotiatedVersion;

    GUID guid;
    PWLAN_INTERFACE_INFO_LIST pInterfaceList = NULL;
    PWLAN_AVAILABLE_NETWORK_LIST pIfList = NULL;
    fWlanOpenHandle WlanOpenHandle = NULL;
    fWlanEnumInterfaces WlanEnumInterfaces = NULL;
    fWlanGetAvailableNetworkList WlanGetAvailableNetworkList = NULL;
    fWlanCloseHandle WlanCloseHandle = NULL;
    fWlanFreeMemory WlanFreeMemory = NULL;
    WLAN_AVAILABLE_NETWORK wlanAN;

    TRY
    {
        hInstLibrary = LoadLibrary("wlanapi.dll");
        ASSERT(!(WlanOpenHandle = (fWlanOpenHandle)GetProcAddress(hInstLibrary, "WlanOpenHandle")), 0);
        ASSERT(!(WlanEnumInterfaces = (fWlanEnumInterfaces)GetProcAddress(hInstLibrary, "WlanEnumInterfaces")), 0);
        ASSERT(!(WlanGetAvailableNetworkList = (fWlanGetAvailableNetworkList)GetProcAddress(hInstLibrary, "WlanGetAvailableNetworkList")), 0);
        ASSERT(!(WlanCloseHandle = (fWlanCloseHandle)GetProcAddress(hInstLibrary, "WlanCloseHandle")), 0);
        ASSERT(!(WlanFreeMemory = (fWlanFreeMemory)GetProcAddress(hInstLibrary, "WlanFreeMemory")), 0);
        ASSERT(WlanOpenHandle(CLIENT_VERSION_2, NULL, &dwNegotiatedVersion, &hClientHandle), ERROR_SUCCESS);
        ASSERT(WlanEnumInterfaces(hClientHandle, NULL, &pInterfaceList), ERROR_SUCCESS);

        guid = pInterfaceList->InterfaceInfo[0].InterfaceGuid;
        ASSERT(WlanGetAvailableNetworkList(hClientHandle, &guid, WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES, NULL, &pIfList), ERROR_SUCCESS);

        printf("%32s|%13s|\n", "SSID", "Quality");
        for (i = 0; i < (int)pIfList->dwNumberOfItems; i++)
        {
            wlanAN = pIfList[0].Network[i];
            printf("%32s|%10ddBm|\n", wlanAN.dot11Ssid.ucSSID, convert_quality_to_dbm(wlanAN.wlanSignalQuality));
        }

        WlanCloseHandle(hClientHandle, NULL);
        WlanFreeMemory(pInterfaceList);
        WlanFreeMemory(pIfList);
        FreeLibrary(hInstLibrary);

        return 0;
    }
    CATCH
    {
        if (hClientHandle) WlanCloseHandle(hClientHandle, NULL);
        if (pInterfaceList) WlanFreeMemory(pInterfaceList);
        if (pIfList) WlanFreeMemory(pIfList);
        FreeLibrary(hInstLibrary);

        return -1;
    }
}
